package com.yami.shop.mystery.common.listener;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.event.OpenBoxFailEvent;
import com.yami.shop.mystery.common.dao.MysteryBoxOpenRecordMapper;
import com.yami.shop.mystery.common.dao.MysteryBoxUserArkMapper;
import com.yami.shop.mystery.common.model.MysteryBoxOpenRecord;
import com.yami.shop.mystery.common.model.MysteryBoxUserArk;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Component("openBoxEventFailListener")
@AllArgsConstructor
public class OpenBoxEventFailListener {
    private final MysteryBoxOpenRecordMapper mysteryBoxOpenRecordMapper;

    private final MysteryBoxUserArkMapper mysteryBoxUserArkMapper;

    @EventListener(OpenBoxFailEvent.class)
    @Transactional(rollbackFor = Exception.class)
    public void openBoxEventFailListener(OpenBoxFailEvent event) {
        // 回退开合记录状态为预开启0
        MysteryBoxOpenRecord record = mysteryBoxOpenRecordMapper.selectById(event.getMysteryBoxOpenRecordId());
        record.setStatus(0);
        mysteryBoxOpenRecordMapper.updateById(record);
        // 退还开盒次数
        MysteryBoxUserArk mysteryBoxUserArk = mysteryBoxUserArkMapper.selectOne(new LambdaQueryWrapper<MysteryBoxUserArk>().eq(MysteryBoxUserArk::getUid, event.getUserId()).eq(MysteryBoxUserArk::getBid,record.getBid()));
        mysteryBoxUserArk.setCount(mysteryBoxUserArk.getCount() + 1);
        mysteryBoxUserArkMapper.updateById(mysteryBoxUserArk);
    }
}
